package com.atguigu.cart.sevice.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.atguigu.cart.mapper.CartMapper;
import com.atguigu.cart.sevice.CartService;
import com.atguigu.clients.ProductClient;
import com.atguigu.param.ProductIdsParam;
import com.atguigu.pojo.Cart;
import com.atguigu.pojo.Product;
import com.atguigu.utils.R;
import com.atguigu.vo.CartVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductClient client;

    @Override
    public R save(Cart cart) {

        // 微服务调用商品模块，查询商品信息
        Product product = client.id(cart.getProductId());
        if(product == null){
            return R.fail("该商品已被删除，无法添加到购物车");
        }

        // 检查是否已经达到最大库存
        if(product.getProductNum()==0){
            R fail = R.fail("该商品已没有库存，无法添加");
            fail.setCode("003");
            return fail;
        }

        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId());
        queryWrapper.eq("product_id",cart.getProductId());

        Cart cart1 = cartMapper.selectOne(queryWrapper);
        if(cart1 == null){//第一次插入

            cart1 = new Cart();
            cart1.setUserId(cart.getUserId());
            cart1.setProductId(cart.getProductId());
            cart1.setNum(1);
            cartMapper.insert(cart1);
            return R.ok("添加购物车成功",new CartVo(product,cart1));


        }else{//不是第一次插入，则num字段数量+1即可
            cart1.setNum(cart1.getNum()+1);
            cartMapper.updateById(cart1);
            R ok = R.ok("商品已在购物车，数量+1");
            ok.setCode("002");
            return ok;
        }
    }

    @Override
    public R list(Cart cart) {

        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId());
        List<Cart> carts = cartMapper.selectList(queryWrapper);
        if(carts==null || carts.size()==0){
            return R.fail("该用户在购物车中没有数据");
        }

        // 用户的商品id列表
        ArrayList<Integer> productIds = new ArrayList<>();
        for (Cart cart1 : carts) {
            productIds.add(cart1.getProductId());
        }

        // 获取商品列表
        ProductIdsParam productIdsParam = new ProductIdsParam();
        productIdsParam.setProductIds(productIds);

        // 利用fastjson解析
        Object data = client.ids(productIdsParam).getData();
        String json = JSONObject.toJSONString(data);
        List<Product> products = JSONObject.parseObject(json, new TypeReference<List<Product>>(){});


        // 列表转map
        Map<Integer, Product> map = products.stream().collect(Collectors.toMap(Product::getProductId, v -> v));
        System.out.printf("map="+map);

        // 封装为Vo对象
        ArrayList<CartVo> list = new ArrayList<>();
        for (Cart cart1 : carts) {
            CartVo cartVo = new CartVo(map.get(cart1.getProductId()), cart1);
            list.add(cartVo);
        }

        return R.ok("查询成功",list);

    }

    @Override
    public R update(Cart cart) {

        Product product = client.id(cart.getProductId());
        if(cart.getNum()>product.getProductNum()){
            return R.fail("购物车修改失败,库存不足");
        }

        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId());
        queryWrapper.eq("product_id",cart.getProductId());
        cartMapper.update(cart,queryWrapper);
        return R.ok("购物车修改成功");
    }

    @Override
    public R remove(Cart cart) {

        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId());
        queryWrapper.eq("product_id",cart.getProductId());
        cartMapper.delete(queryWrapper);
        return R.ok("删除购物车数据成功");
    }

    @Override
    public void removeByIds(List<Integer> cartIds) {
        cartMapper.deleteBatchIds(cartIds);
    }
}
